package com.heimali.happyreader.utils;

import java.util.ArrayList;
import java.util.List;

public class ArrayUtils {
	public static Object[] slice(Object[] array, int offset) {
		int length = array.length-offset;
		if (length <= 0 || offset < 0) {
			return new Object[]{};
		}
		return slice(array, offset, array.length-offset);
	}
	
	/**
	 * 从数组中取出一段
	 * @param array
	 * @param offset 偏移量
	 * @param length 取长度-1到倒数第一个， 1表示1个
	 * @return
	 */
	public static Object[] slice(Object[] array, int offset, int length) {
		if (length == 0 || offset < 0) {
			return new Object[]{};
		}
		
		int oldLen = array.length;
		if (length < 0) {
			length = oldLen + length;
		}
		
		length = Math.min(length, oldLen - offset);
		Object[] subArray = new Object[length];
		for(int i=0; i<length; i++) {
			subArray[i] = array[offset + i];
		}
		return subArray;
	}
	
	/**
	 * 截取数组中的一部
	 * @param input
	 * @param offset
	 * @param length
	 * @return List 第一部分是截取后剩余数组， 第二部分是截取的部分
	 */
	public static List<Object[]> splice(Object[] input, int offset, int length) {
		List<Object[]> res = new ArrayList<Object[]>();
		
		if (length == 0 || offset < 0) {
			res.add(input);
			res.add(new Object[]{});
			return res;
		}
	
		int oldLen = input.length, newLen = 0;
		if (length < 0) {
			length = oldLen + length;
		}
		
		length = Math.min(length, oldLen - offset);
		newLen = oldLen - length;
		Object[] subArray = new Object[length];
		Object[] newArray = new Object[oldLen - length];
		for(int i=0; i<offset; i++) {
			newArray[i] = input[i];
		}
		for(int i=0; i<length; i++) {
			subArray[i] = input[offset + i];
		}
		for(int i=offset; i<newLen; i++) {
			newArray[i] = input[length + i];
		}
		
		res.add(newArray);
		res.add(subArray);
		return res;
	}
}
